<template lang="pug">
.page
  .form-shebao-title.font-16.font-weight 手工调账
  Row.font-16.pl-14.mb-20
    Col(span="8") 账单月份：{{currentPeriodYear}}年{{currentPeriodMonth}}月
    Col.ellipsis(span="12") 单位名称：{{currentCompanyName}}
  .pall-20.bg-white.mb-20
    Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="160")
      FormItem.form-item.ivu-col.ivu-col-span-6(label="调账类型：")
        Select(v-model="formData.Category" placeholder="请选择调账类型")
          Option(v-for="(c_item, c_index) of arrListDown.HandleType" :key="c_index" :value="c_item.label") {{c_item.label}}
      .clearfix
      FormItem.form-item.ivu-col.ivu-col-span-6(v-for="(item, index) of formItem" :label="item.isPersonalBurden ? item.InsuranceName + '(个人)：' : item.InsuranceName + '(单位)：'" :key="index")
        Input(v-model="item.Amt" placeholder="请输入" type="number")
      .clearfix
      FormItem.form-item.ivu-col.ivu-col-span-24(label="备注：")
        Input(v-model="formData.Remark" placeholder="请输入" type="textarea" :rows="3")
    .clearfix.text-center
      Button(type="info" ghost @click="handleAddTemp") 添加到表格

  .clearfix(v-if="tableData.length")
    Table.ivu-table-overflowY-hidden.beautiful-table.mb-20(:columns="thead" :data="tableData" :stripe="true")
      template(slot-scope="{ row, index }" slot="action")
        Button(type="text" size="small" @click="handleDelRow(index)") 删除
  .clearfix.text-center
    Button(type="info" @click="handleSubmit") 保存
</template>

<script>
import { BillApi } from '@/api/Bill.api.js'
import { adjustBillThead } from './CBtableHead.js'
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'

export default {
  name: 'AdjustBill',

  components: {
  },

  data () {
    return {
      currentPeriodYear: null,
      currentPeriodMonth: null,
      currentCompanyName: null,
      currentCompanyId: null,
      // thead: _cloneDeep(adjustBillThead),
      thead: [{ title: '调账类型', key: 'category', minWidth: 100 }],
      tableData: [],
      formData: {
        Category: '',
        Remark: ''
      },
      formItem: [],
      rules: {
        billingMethod: [
          { required: true, message: '请选择开票方式' }
        ],
        invoiceDetail: [
          { required: true, message: '请选择开票明细' }
        ]
      },
      arrListDown: {
        HandleType: [],
      },
      tableParams: [],
      handleDatas: []
    }
  },

  watch: {
  },

  mounted () {
    this.currentPeriodYear = this.$route.query.periodYear
    this.currentPeriodMonth = this.$route.query.periodMonth
    this.currentCompanyId = this.$route.query.companyId
    this.currentCompanyName = this.$route.query.companyName
    console.log('❤ this.currentCompanyId：', this.currentCompanyId)

    this.getEnum()
    this.getProgramNames()
    this.getHandelList()
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    }
  },

  methods: {
    // 数据字典
    getEnum () {
      let typeName = 'HandleType'
      Common.getSelectValueList(typeName, this.arrListDown)
    },

    // 添加到表格
    handleAddTemp () {
      var sum = 0
      this.formItem.map(item => {
        if (item.Amt) {
          sum += parseInt(item.Amt)
        }
      })
      var tableCategoryArr = []
      this.tableData.map(item => {
        tableCategoryArr.push(item.category)
      })

      if (!this.formData.Category) {
        this.$Message.warning({
          content: '请选择调账类型',
          // duration: 0,
          closable: true
        })
      } else if (tableCategoryArr.indexOf(this.formData.Category) !== -1) {
        this.$Message.warning({
          content: '调账类型已存在，请删除原来的记录再进行重新录入',
          duration: 5,
          closable: true
        })
      } else if (sum == 0) {
        this.$Message.warning({
          content: '请输入有效的数字',
          // duration: 0,
          closable: true
        })
      } else {
        // 用于表格展示效果
        var feeList = []
        var row = {}
        this.formItem.map(item => {
          if (item.Amt) {
            var str = item.isPersonalBurden ? item.insuranceCode + 'EmployeeAmt' : item.insuranceCode + 'CompanyAmt'
            feeList.push({...item, ...{[str]: item.Amt}})
            row = {...row, ...{[str]: item.Amt}, ...{category: this.formData.Category}}
          }
        })
        this.tableData.push(row)

        var handleDatas = {
          category: this.formData.Category,
          remark: this.formData.Remark,
          feeList: feeList
        }
        this.handleDatas.push(handleDatas)

        // 所有值清空
        Object.keys(this.formData).forEach(key => {
          this.formData[key] = ''
        })
        this.formItem.map(item => {
          item.Amt = ''
        })
        console.log('this.tableData: ', this.tableData)
      }
    },

    // 从表格中删除
    handleDelRow (index) {
      this.tableData.splice(index, 1)
      this.handleDatas.splice(index, 1)
    },

    // 获取处理历史数据
    async getHandelList () {
      var params = {
        periodYear: this.currentPeriodYear,
        periodMonth: this.currentPeriodMonth,
        companyID: this.currentCompanyId
      }
      let res = await BillApi.getHandelList(params)
      console.log('获取处理历史数据res: ', res)
      var tempTableArr = []
      if (res.status === 200 && res.data.success) {
        this.handleDatas = res.data.data
        var result = res.data.data
        result.map(item => {
          var tempObj = {}
          item.feeList.map(c_item => {
            var str = c_item.isPersonalBurden ? c_item.insuranceCode + 'EmployeeAmt' : c_item.insuranceCode + 'CompanyAmt'
            tempObj = {...tempObj, ...{[str]: c_item.amt}, ...{category: item.category}}
          })
          tempTableArr.push(tempObj)
        })
      }
      this.tableData = tempTableArr
      console.log('❤ this.tableData: ', this.tableData)
    },

    // 获取险种
    async getProgramNames () {
      let res = await BillApi.getProgramNames()
      console.log('获取险种res: ', res)
      if (res.status === 200 && res.data.success) {
        res.data.data.map(item => {
          this.formItem.push(
            {isPersonalBurden: false, InsuranceType: item.group, insuranceCode: item.code, InsuranceName: item.name, Amt: ''},
            {isPersonalBurden: true, InsuranceType: item.group, insuranceCode: item.code, InsuranceName: item.name, Amt: ''}
          )

          this.thead.push(
            {title: item.name + '(单位)', key: item.code + 'CompanyAmt', width: item.name.length >= 5 ? 180 : 130},
            {title: item.name + '(个人)', key: item.code + 'EmployeeAmt', width: item.name.length >= 5 ? 180 : 130}
          )
        })
        this.thead.push({title: '操作', key: 'action', slot: 'action', fixed: 'right', width: 100})
      }
    },

    // 添加手动处理账单
    async handleSubmit () {
      // 用于发送请求
      var tempParams = {
        periodYear: this.currentPeriodYear,
        periodMonth: this.currentPeriodMonth,
        companyID: this.currentCompanyId,
        companyName: this.currentCompanyName,
        insureNo: '',
        handleDatas: this.handleDatas
      }
      console.log('tempParams: ', tempParams)
      let res = await BillApi.handleBill(tempParams)
      console.log('添加手动处理账单res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.getHandelList()
      } else {
        this.$Message.warning({
          content: res.data.message,
          // duration: 0,
          closable: true
        })
      }
    }
  } // methods end
}
</script>

<style lang="less" scope>
</style>
